import React, { useEffect } from 'react'
import axios from 'axios'
import {Table,Button,Tag, notification} from 'antd'

export default function AuditList() {
  const {username}=JSON.parse(localStorage.getItem('token'))
  const [state,SetState]=React.useState([])
  const auditList=["未审核", '审核中', '已通过', '未通过'];

  useEffect(()=>{
    axios.get(`http://localhost:8000/news?author=${username}&auditState_ne=0&publishState_lte=1`).then(res=>{
      SetState(res.data)
    })
  },[])
  console.log(state);
  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      render:(title,item)=>{
        return<a href={`/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'categoryId',
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      render:(auditState)=> {
        return <div>
          {
             auditState===1&&<Tag color="orange">{auditList[auditState]}</Tag>
          }
            {
             auditState===2&&<Tag color="green">{auditList[auditState]}</Tag>
          }
            {
             auditState===3&&<Tag color="red">{auditList[auditState]}</Tag>
          }
        </div>
      },
    },
    {
      title: '操作',
      // dataIndex: 'auditState',
      render:(item)=>{
        return <div>
        {
          item.auditState===1&&<Button type='primary' onClick={()=>handleRervert(item)}>撤销</Button>
        }
         {
          item.auditState===2&&<Button type='primary' onClick={()=>{handlePublish(item)}}>发布</Button>
        }
         {
          item.auditState===3&&<Button type='primary'   onClick={()=>{
            window.location.href=`/news-manage/update/${item.id}`
          }} >修改</Button>
        }
        </div>  
      }
    },
  ];
 const handleRervert=(item)=>{
  // debugger
    SetState(state.filter(data=>data.id!==item.id));
    axios.patch(`http://localhost:8000/news/${item.id}`,{auditState:0}).then(res=>{
      notification.info({
        message: `通知`,
        description:
          `您可以到草稿箱中查看您的新闻`,
        placement:"bottomRight"
      })
    })
  }
  const handlePublish = (item)=>{
    axios.patch(`http://localhost:8000/news/${item.id}`, {
        "publishState": 2,
        "publishTime":Date.now()
    }).then(res=>{
      window.location.href=`/publish-manage/published`
      // navigate('/publish-manage/published');
        notification.info({
            message: `通知`,
            description:
              `您可以到【发布管理/已经发布】中查看您的新闻`,
            placement:"bottomRight"
        });
    })
}
  return (
    <div>
    <Table dataSource={state} columns={columns} pagination={{ pageSize:5}} rowKey={item=>item.id}/>
  </div>
  )
}
